<template>
    <div>
        <breadcrumb :routes="routes"></breadcrumb>
        <div class="goods-detail">
            <div class="dev-width">
                <div class="goods-show">
                    <div class="goods-pic">
                        <img v-if="demandinfo.hasOwnProperty('demandImageList')" class="goods-big-pic" :src="absUrl(demandinfo.demandImageList[0].fileUrl)" :onerror="defaultImg" />
                        <img v-else src="~/assets/images/requirement.png" />
                    </div>
                    <div class="goods-msg">
                        <span class="title">{{demandinfo.name}}
                            <span v-if='demandinfo.hits>0'>{{demandinfo.hits}}人浏览</span>
                            <span v-if='demandinfo.inquiries>0'>{{demandinfo.inquiries}}人咨询</span>
                        </span>
                        <dl>
                            <dt>需求序号
                            </dt>
                            <dd>{{demandinfo.no}}</dd>
                        </dl>
                        <dl>
                            <dt>需求类型
                            </dt>
                            <dd>{{getDemandType()}}</dd>
                        </dl>
                        <dl>
                            <dt>合作方式
                            </dt>
                            <dd>{{getCooperationMode()}}</dd>
                        </dl>
                        <dl>
                            <dt>意向价格
                            </dt>
                            <dd v-if="demandinfo.hasOwnProperty('intendedPrice')">
                                <b>{{demandinfo.intendedPrice!=0?'¥ '+ demandinfo.intendedPrice.toLocaleString()+' 元':'面议'}}
                                </b>
                            </dd>
                        </dl>

                        <div class="goods-btns">
                            <a class="btn-blue" @click="zixun">咨询</a>
                            <a class="btn-orange" v-if='isTechManager' @click="ch">撮合</a>
                            <a class="btn-red" v-if='isOneself' @click="collection">{{collectionStatus?'收藏':'取消收藏'}}</a>
                        </div>
                    </div>
                </div>
                <div class="goods-detail-long">
                    <div class="shop-box">
                        <h3 style="font-size: 14px;color: #999999;margin: 0 0 10px;">
                            <span>
                                <i class="iconfont icon-mingpian"></i>需求方信息
                            </span>
                        </h3>

                        <h4 style="padding:12px 12px 0px 0px;font-size: 14px;color: #333333;">
                            <span>{{demandinfo.linkman}}</span>
                        </h4>
                        <p style="padding:0 0px 12px 0px;">
                            <span style="color: #666666;">电话</span>
                            <span style="color: #666666;margin-left: 10px;">{{demandinfo.phone}}</span>
                        </p>
                    </div>
                    <div class="goods-detail-main">
                        <Tabs type="card">
                            <TabPane label="需求详情" style="overflow:hidden">
                                <div v-html='demandinfo.description'></div>
                            </TabPane>
                            <TabPane label="需求摘要">
                                <pre class="pre">{{demandinfo.summary}}</pre>
                            </TabPane>
                            <TabPane label="详细参数">
                                <table class="goods-two">
                                    <tbody v-if="this.demandinfo.type=='01'">
                                        <tr>
                                            <td class="label">需求类型</td>
                                            <td>{{getDemandType()}}</td>
                                            <td class="label">所处阶段</td>
                                            <td>{{getStage()}}</td>
                                            <td class="label">发布方</td>
                                            <td>{{getPublishType()}}</td>
                                        </tr>
                                        <tr>
                                            <td class="label">交易方式</td>
                                            <td>{{getCooperationMode()}}</td>
                                            <td class="label">所在地区</td>
                                            <td style="width: 180px">
                                                <my-selector :value="getRegion()" type="text"></my-selector>
                                            </td>
                                            <td class="label"> 需求标签</td>
                                            <td>{{getTags()}}</td>
                                        </tr>
                                        <tr>
                                            <td class="label"> 信息有效期至</td>
                                            <td>{{demandinfo.publishValidityTime|formatDate('yyyy-MM-dd') ||'长久有效' }}</td>
                                            <td class="label" style="width:135px">高新技术领域分类</td>
                                            <td colspan="3" style="font-size:12px;">{{demandinfo.highCooperationName}}</td>
                                        </tr>
                                    </tbody>
                                    <tbody v-else>
                                        <tr>
                                            <td class="label">需求类型</td>
                                            <td>{{getDemandType()}}</td>
                                            <td class="label">发布方</td>
                                            <td>{{getPublishType()}}</td>
                                            <td class="label"> 需求标签</td>
                                            <td style="font-size:12px;width:240px;line-height:17px">{{getTags()}}</td>
                                        </tr>
                                        <tr>
                                            <td class="label">交易方式</td>
                                            <td>{{getCooperationMode()}}</td>
                                            <td class="label">所在地区</td>
                                            <td style="width: 180px">
                                                <my-selector :value="getRegion()" type="text" :level="2"></my-selector>
                                            </td>
                                            <td class="label"> 信息有效期至</td>
                                            <td>{{demandinfo.publishValidityTime|formatDate('yyyy-MM-dd') ||'长久有效'}}</td>
                                        </tr>
                                        <tr>
                                            <td class="label" style="width:135px">高新技术领域分类</td>
                                            <td colspan="4" style="font-size:12px;width:200px">
                                                {{demandinfo.highCooperationName}}
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </TabPane>
                        </Tabs>
                    </div>
                </div>
            </div>
        </div>
        <Modal v-model="loginVisible" width="360">
            <p slot="header" style="color:#f60;text-align:center">
            </p>
            <div style="text-align:center">
                <p> 抱歉，您没有登录无权访问该页面!</p>
                <nuxt-link :to="{path:'/login',query:{
                  callback:''
                }}" class="h_l">立即登录
                </nuxt-link>
            </div>
            <div slot="footer">
            </div>
        </Modal>
        <Modal v-model="realNameVisible" width="360">
            <p slot="header" style="color:#f60;text-align:center">
            </p>
            <div style="text-align:center">
                <p> 抱歉，您没有实名认证无权访问该页面!</p>
                <a :href="businessBrowserUrl+'/realname'" class="h_l">立即实名认证</a>
            </div>
            <div slot="footer">
            </div>
        </Modal>
        <Modal class="confirm-dialog" v-model="contactPhoneVisible" width="360">
            <p slot="header" style="color:#f60;text-align:center">
                联系方式
            </p>
            <div>
                <div style="padding:10px 30px;">
                    <h4 style="text-align: left;">
                        <span>需求方信息:{{demandinfo.linkman}}</span>
                    </h4>
                    <div style="text-align: left;">
                        <span class="phoneNumber">{{realPhone?'联系电话:'+realPhone:'未留联系电话,请联系平台'}}</span>
                    </div>
                </div>
            </div>
            <div slot="footer">
                <Button class="long" @click="contactPhoneVisible=false">关闭</Button>
            </div>
        </Modal>
        <Modal class="confirm-dialog" v-model="collectionVisible" :mask-closable="false" width="360">
            <p slot="header">
                确认{{collectionStatus?'收藏':'取消收藏'}}需求吗
            </p>
            <div slot='footer' style="width:100%;">
                <Button type="text" style="background: #F8F6F6; color: #666666;" @click='collectionVisible=false'>取消
                </Button>
                <Button type="text" @click='collectionConfirm'>确认</Button>
            </div>
        </Modal>
        <Modal v-model="showGoodVisible" :mask-closable="false" width="462">
            <div slot="header">
                选择与需求契合的技术
            </div>
            <div class="modal-main" style="padding: 0 20px">
                <Input v-model="page.keyword" icon=" iconfont icon-index_seatch" placeholder="根据技术成果或专利名称快速选择..." style="width:100%" @on-click="newGetData" />
                <Checkbox class="cb" v-model="page.isRecommended" @on-change="newGetData">仅显示推荐的
                </Checkbox>
            </div>
            <div class="goods-table">
                <Scroll :on-reach-bottom="reachBottom" height="258">
                    <Table ref="multipleTable" @on-selection-change="selectionChange" :columns="columns1" :data="goodsList" :show-header="showHeader"></Table>
                </Scroll>
            </div>
            <div class="tip">
                <span>共
                    <a>{{total}}</a>个可撮合商品</span>
                <span style="margin-left: 20px">可选（
                    <a style="color:#FB9109">{{matchOperation.ids.length}}</a>/3）个</span>
            </div>
            <div slot="footer">
                <Button type="text" style="width:50%;background: #F8F6F6; color: #666666;" @click="showGoodVisible = false">取消
                </Button>
                <Button type="text" :disabled="matchOperation.ids.length===0" @click="show4">确认</Button>
            </div>
        </Modal>
        <Modal v-model="matchedGoodVisible" :mask-closable="false" width="462">
            <div slot="header">
                提交撮合
            </div>
            <div class="modal-main" style="padding: 0 20px">
                本次撮合商品
            </div>
            <div class="goods-table">
                <Table :columns="columns2" :data="selection" :show-header="showHeader"></Table>
            </div>
            <div class="tip">
                撮合建议
                <Input v-model="matchOperation.advice" type="textarea" placeholder="请填写撮合建议500字以内..." />
            </div>
            <div slot="footer">
                <Button type="text" style="width:50%;background: #F8F6F6; color: #666666;" @click="matchedGoodVisible = false">
                    返回
                </Button>
                <Button type="text" @click="makeMatch">立即撮合</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
import portal from "~/net/portal"
import { searchCodes } from "~/constant/SearchCodes"
import myProgress from '~/components/Myprogress'
import breadcrumb from '~/components/Breadcrumb'
import { absUrl } from '~/utils/tool'
import mySelector from '~/components/my-Selector'
import config from "~/config"
import { mapState } from 'vuex'

export default {
    head() {
        return {
            title: '需求详情'
        }
    },
    components: {
        myProgress,
        breadcrumb,
        mySelector
    },
    computed: {
        ...mapState(['user', 'identities']),
        routes() {
            return [
                { name: '首页', path: '/' },
                { name: '需求' },
                { name: this.demandinfo.name }
            ]
        },
        isTechManager() {
            return this.user != null && Array.isArray(this.identities) && (this.identities.length > 0 && this.identities[0].type == '01')
        },
        isOneself() {
            if (this.user !== null && (this.demandinfo.userId !== null)) {
                return this.user.id !== this.demandinfo.userId
            } else {
                return true
            }
        }
    },
    created() {
        if (typeof (this.$route.query.id) != 'undefined') {
            this.page.demandId = this.$route.query.id;
            this.demandId = this.$route.query.id;
        }
        if (typeof (this.$route.query.show) != 'undefined') {
            this.show = false;
        }
        // this.queryCollection()
    },
    async asyncData(context) {
        let [resp1, resp2] = await Promise.all([
            portal.getDetailByDemandId({
                query: {
                    demanId: context.query["id"],
                    hits: typeof (context.query["show"]) == 'undefined' ? true : false
                },
                client: context.req
            }),
            portal.judgeCollected({
                query: {
                    id: context.query["id"],
                    type: '01'
                },
                client: context.req
            })
        ]);
        let data1 = resp1.data;

        let data2 = resp2.data;
        return {
            demandinfo: data1,
            collectionStatus: (data2 == '01') ? true : false,
            collectStatus: (data2 === '01') ? '00' : '01'
        }

    },

    data() {
        return {
            collectStatus: '',
            contactPhoneVisible: false,
            demandId: '',
            absUrl,
            show: true,
            collectionVisible: false,
            collectionStatus: true,
            loginVisible: false,
            realNameVisible: false,
            showGoodVisible: false,
            matchedGoodVisible: false,
            codes: searchCodes,
            businessBrowserUrl: config.businessBrowserUrl,
            demandinfo: {},
            realPhone: '',
            showHeader: false,
            total: 0,
            lastPage: false,
            page: {
                page: 1,
                rows: 15,
                keyword: '',
                isRecommended: false,
                demandId: 1
            },
            selection: [],
            matchOperation: {
                ids: [],
                advice: ''
            },
            columns1: [{
                width: 20
            }, {
                type: 'selection',
                width: 24,
                align: 'left'
            }, {
                width: 47,
                align: 'left',
                render: (h, params) => {
                    return h('img', {
                        'class': 'goodsPic',
                        attrs: {
                            'src': this.absUrl(params.row.titleImgUrl)
                        }
                    })
                }
            }, {
                width: 200,
                key: 'goodsName',
                align: 'left',
                render: (h, params) => {
                    return h('span', {
                        'class': 'texts'
                    }, params.row.goodsName)
                }
            }, {
                width: 36,
                align: 'center',
                key: 'recommended',
                render: (h, params) => {
                    return h('i', {
                        'class': params.row.recommended ? 'iconfont icon-diamond' : ''
                    });
                }
            }, {
                width: 50,
                key: 'matchingRate',
                render: (h, params) => {
                    return h('Tooltip', {
                        props: {
                            trigger: 'hover',
                            placement: 'top',
                            content: '需求与商品契合度'
                        }
                    }, [
                            h('my-progress', {
                                props: {
                                    percent: params.row.matchingRate
                                }
                            })
                        ])
                }
            }, {
                width: 7
            }, {
                width: 58,
                key: 'ownerName',
                align: 'right',
                render: (h, params) => {
                    return h('span', {
                        'class': 'texts'
                    }, params.row.ownerName)
                }
            }, {
                width: 20
            }],
            columns2: [{
                width: 20
            }, {
                width: 47,
                align: 'left',
                render: (h, params) => {
                    return h('img', {
                        'class': 'goodsPic',
                        attrs: {
                            'src': this.absUrl(params.row.titleImgUrl)
                        }
                    })
                }
            }, {
                width: 224,
                key: 'goodsName',
                align: 'left',
                render: (h, params) => {
                    return h('span', {
                        'class': 'texts'
                    }, params.row.goodsName)
                }
            }, {
                width: 36,
                align: 'center',
                key: 'recommended',
                render: (h, params) => {
                    return h('i', {
                        'class': params.row.recommended ? 'iconfont icon-diamond' : ''
                    });
                }
            }, {
                width: 50,
                key: 'matchingRate',
                render: (h, params) => {
                    return h('Tooltip', {
                        props: {
                            trigger: 'hover',
                            placement: 'top',
                            content: '需求与商品契合度'
                        }
                    }, [
                            h('my-progress', {
                                props: {
                                    percent: params.row.matchingRate
                                }
                            })
                        ])
                }
            }, {
                width: 7
            }, {
                width: 58,
                key: 'ownerName',
                align: 'right',
                render: (h, params) => {
                    return h('span', {
                        'class': 'texts'
                    }, params.row.ownerName)
                }
            }, {
                width: 20
            }],
            goodsList: []
        }
    },
    methods: {
        defaultImg() {
            return 'this.src="' + require(`~/assets/images/requirement.png`) + '"'
        },
        getDemandType() {
            if (this.demandinfo.type == '00') {
                return '专利'
            } else if (this.demandinfo.type == '01') {
                return '技术成果'
            } else {
                return '专利/技术成果'
            }
        },
        getCooperationMode() {
            var cooperationMode = ''
            switch (this.demandinfo.cooperationMode) {
                case '00':
                    cooperationMode = '股权投资'
                    break;
                case '01':
                    cooperationMode = '技术转让'
                    break;
                case '02':
                    cooperationMode = '许可使用'
                    break;
                case '03':
                    cooperationMode = '合作开发'
                    break;
                case '04':
                    cooperationMode = '合作兴办新企业'
                    break;
                case '05':
                    cooperationMode = '其他'
                    break;
            }
            return cooperationMode
        },
        getStage() {
            var stage = ''
            switch (this.demandinfo.stage) {
                case '00':
                    stage = '实验室'
                    break;
                case '01':
                    stage = '小试'
                    break;
                case '02':
                    stage = '中试'
                    break;
                case '03':
                    stage = '产业化'
                    break;
            }
            return stage;
        },
        getPublishType() {
            if (this.demandinfo.publisherType == '0') {
                return '个人'
            } else {
                return '单位'
            }
        },
        getTags() {
            if (typeof (this.demandinfo.demandTags) != 'undefined') {
                return this.demandinfo.demandTags.join(",")
            } else
                return ''
        },
        getRegion() {
            if (typeof (this.demandinfo.region) != 'undefined') {
                return this.demandinfo.region.split(',')
            } else
                return []
        },
        newGetData() {
            this.goodsList = [];
            this.selection = [];
            this.lastPage = false;
            this.page.page = 1;
            this.getAssociatedGoods();
        },

        reachBottom() {
            if (this.lastPage) {
                this.$Message.info('没有更多商品了');
            } else {
                this.page.page += 1;
                this.getAssociatedGoods();
            }
        },
        ch() {
            this.page.isRecommended = false;
            this.page.keyword = '';
            this.newGetData();
        },
        getAssociatedGoods() {
            let _this = this;
            portal.getAssociatedGoods({
                query: this.page
            }).then((res) => {
                let { code, data, message } = res;
                if (code === '0000') {
                    this.total = data.total;
                    if (data.total !== 0) {
                        data.rows.forEach(function (item) {
                            item._disabled = _this.selection.length === 3;
                            _this.goodsList.push(item);
                        });
                    }
                    this.lastPage = data.lastPage;
                    this.showGoodVisible = true;
                }
            })
        },
        //收藏需求  传收藏id  命名接口 demandCollection
        collectionConfirm(collectionStatus) {
            portal.setCollectStatus({
                query: {
                    id: this.demandId,
                    type: '01',
                    status: this.collectStatus
                },
            }).then((res) => {
                let { code, message } = res;
                if (code === '0000') {

                    if (this.collectStatus === '00') {
                        this.collectStatus = '01'
                        this.collectionVisible = false;
                        this.collectionStatus = false
                        this.$Message.success('收藏成功');
                    } else {
                        this.collectStatus = '00'
                        this.collectionVisible = false;
                        this.collectionStatus = true
                        this.$Message.success('已取消收藏');
                    }

                } else {
                    this.$Message.error(message);
                }
            })
        },

        makeMatch() {
            if (this.matchOperation.advice.length > 500) {
                this.$Message.error('撮合建议兺呢个超过500字');
                return;
            }
            portal.makeMatch({
                query: {
                    demandId: this.page.demandId,
                    suggestion: this.matchOperation.advice
                },
                body: this.matchOperation.ids
            }).then((res) => {
                let { code, data, message } = res;
                if (code === '0000') {
                    this.matchedGoodVisible = false;
                    this.showGoodVisible = false;
                    this.$Message.success('撮合成功');
                } else {
                    this.$Message.error(message);
                }
            })
        },
        zixun() {
            if (this.user == null) {
                this.loginVisible = true;
                return;
            }
            if (this.user.userStatus != 2 && this.user.userStatus != 5) {
                this.realNameVisible = true;
                return;
            }
            // if (this.contactPhoneVisible !== true)
            //     portal.getPhoneByDemandId({
            //         query: {
            //             demanId: this.demandinfo.id
            //         }
            //     }).then(res => {
            //         this.demandinfo.phone = res.data
            //         // this.$Message.success('请查看需求联系人手机')
            //         this.contactPhoneVisible !== true
            //     })

            if (this.realPhone !== undefined)
                portal.getPhoneByDemandId({
                    query: {
                        demanId: this.demandinfo.id
                    }
                }).then(res => {
                    this.demandinfo.phone = res.data
                    this.realPhone = res.data
                    this.contactPhoneVisible = true;
                    // this.$Message.success('请查看需求联系人手机')
                })
        },
        collection() {
            if (this.user == null) {
                this.loginVisible = true;
                return;
            }
            if (this.user !== null) {
                this.collectionVisible = true;
                return;
            }
        },
        filterChildType(childType) {
            if (childType.startsWith("01")) {
                return this.codes[1].childs.find(_ => _.code == childType).name;
            } else if (childType.startsWith("02")) {
                return this.codes[2].childs.find(_ => _.code == childType).name;
            } else return "";
        },
        show4() {
            this.matchOperation.advice = '';
            this.matchedGoodVisible = true;
        },
        selectionChange(value) {
            this.selection = value;
            let _this = this;
            this.matchOperation.ids = [];
            this.selection.forEach(function (item) {
                _this.matchOperation.ids.push(item.goodId);
            });
            if (this.selection.length === 3) {
                this.goodsList.forEach(function (item) {
                    if (item.goodId === _this.matchOperation.ids[0] || item.goodId === _this.matchOperation.ids[1] || item.goodId === _this.matchOperation.ids[2]) {
                        item._disabled = false;
                        item._checked = true;
                    } else {
                        item._disabled = true;
                    }
                });
                console.log(this.goodsList);
            } else {
                this.goodsList.forEach(function (item) {
                    item._disabled = false;
                    item._checked = item.goodId === _this.matchOperation.ids[0] || item.goodId === _this.matchOperation.ids[1] || item.goodId === _this.matchOperation.ids[2];
                });
            }
        }
    }
}
</script>
<style>
@import "~/assets/styles/goods-detail.css";
@import "~/assets/styles/dialog.css";
</style>